/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.core.param;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfast.framework.web.core.Action;

/**
 * MethodPara接口实例创建者
 * @author zengjintao
 * @version 1.0
 * @createTime 2018年1月6日下午9:16:40
 */
public class ParaBuilder {
	
	private static final ParaBuilder paraBuilder = new ParaBuilder();
	
	private ParaBuilder(){
		
	}
	
	public static final ParaBuilder getParaBuilder(){
		return paraBuilder;
	}
	
	public ParamProcessor builder(Action action, HttpServletRequest request, HttpServletResponse response){
		ParamProcessor paramManager = new ParamProcessor();
		Method method = action.getMethod();
		Parameter[] parameters = method.getParameters();
		for (Parameter parameter : parameters) {
			ActionMethodPara methodPara = createMethodPara(parameter,request,response);
			paramManager.addMethodPara(methodPara);
		}
		return paramManager;
	}

	private ActionMethodPara createMethodPara(Parameter parameter, HttpServletRequest request,HttpServletResponse response) {
		Param param = parameter.getAnnotation(Param.class);
		//优先处理@Param参数
		if(param != null){
			AnnotationPara para = new AnnotationPara(param,request);
			return para;
		}
		Class<?> classType = parameter.getType();
		if(classType.isAssignableFrom(HttpServletRequest.class)){
			HttpServletRequestPara httpServletPara = new HttpServletRequestPara(request);
			return httpServletPara;
		}else if(classType.isAssignableFrom(HttpServletResponse.class)){
			HttpServletResponsePara httpServletPara = new HttpServletResponsePara(response);
			return httpServletPara;
		}
		return null;
	}
}
